package com.ws.common.util;

import org.apache.commons.lang3.StringUtils;

import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Properties;

/**
 * Created by WS on 2018/1/26.
 */
public class CommonUtils {
    public final static String ERROR_MSG_FILE = "error.properties";

    public static String getResultMsg(String code, String[] msgParams) {
        Properties prop = new Properties();
        InputStream in = CommonUtils.class.getClassLoader().getResourceAsStream(ERROR_MSG_FILE);
        try {
            prop.load(in);
            String property = prop.getProperty(filterTailAlpha(code));
            if (null == property) {
                return getReturnMsgIfKeyIsNull(code, msgParams);
            }
            return MessageFormat.format(property, msgParams);
        } catch (Exception e) {
            return "PARSE ERORR";
        }
    }

    private static String filterTailAlpha(String code) {
        String subCode = "";
        if (StringUtils.isNotBlank(code)) {
            for (int i = code.length() - 1; i > 0; i--) {
                if (!Character.isLetter(code.charAt(i))) {
                    subCode = code.substring(0, i + 1);
                    break;
                }
            }
        }
        return StringUtils.isNotBlank(subCode) ? subCode : code;
    }

    private static String getReturnMsgIfKeyIsNull(String code, String[] msgParams) {
        StringBuilder sb = new StringBuilder();
        if (null != msgParams) {
            for (String str : msgParams) {
                sb.append(str).append(" ");
            }
        }
        if (sb.length() == 0) {
            sb.append(code);
        }
        return sb.toString();
    }
}
